<?php

namespace app\admin\controller\wanlshop;

use app\api\model\wanlshop\Pay;
use app\common\controller\Backend;
use app\common\model\Area;
use app\common\model\User;

/**
 * 分红池
 *
 * @icon fa fa-circle-o
 */
class Pond extends Backend
{

    /**
     * Pond模型对象
     * @var \app\admin\model\wanlshop\Pond
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Pond;

        $this->model::event('before_insert', function ($row){return $this->beforeSave($row);});
        $this->model::event('before_update', function ($row){return $this->beforeSave($row);});
    }

    // 处理前端输入的城市，分为三段存储
    protected function beforeSave($row){
        if(in_array($this->request->action(),['add','edit'])){

                if (empty($row->province_id)){
                    exception('请选择省');
                    return false;
                }
                $province_id = isset($row->province_id)?$row->province_id:0;

                $city_id = isset($row->city_id)?$row->city_id:0;

                $district_id = isset($row->district_id)?$row->district_id:0;

                if ($this->request->action()=='add'){

                    if (!empty($row->province_id)&&!empty($row->city_id)&&!empty($row->district_id)){
                        $info = \app\admin\model\wanlshop\Pond::where([
                            'province_id'=>$row->province_id,
                            'city_id'=>$row->city_id,
                            'district_id'=>$row->district_id
                        ])->find();
                        if ($info){
                            exception('该区域分红池已存在');
                            return false;
                        }
                        $province = Area::get($row->province_id);

                        $row->province = $province->getAttr('name');
                        $city = Area::get($row->city_id);
                        $row->city = $city->getAttr('name');
                        $district = Area::get($row->district_id);
                        $row->district = $district->getAttr('name');
                    } elseif (!empty($row->province_id)&&!empty($row->city_id)){
                        $info = \app\admin\model\wanlshop\Pond::where([
                            'province_id'=>$row->province_id,
                            'city_id'=>$row->city_id,
                        ])->find();
                        if ($info){
                            exception('该区域分红池已存在');
                            return false;
                        }
                        $province = Area::get($row->province_id);
                        $row->province = $province->getAttr('name');
                        $city = Area::get($row->city_id);
                        $row->city = $city->getAttr('name');
                    } elseif (!empty($row->province_id)){
                        $info = \app\admin\model\wanlshop\Pond::where([
                            'province_id'=>$row->province_id,
                        ])->find();
                        if ($info){
                            exception('该区域分红池已存在');
                            return false;
                        }
                        $province = Area::get($row->province_id);
                        $row->province = $province->getAttr('name');
                    }

                } else {
                    /*if (!empty($row->province_id)&&!empty($row->city_id)&&!empty($row->district_id)){
                        $info = \app\admin\model\wanlshop\Pond::where([
                            'province_id'=>$row->province_id,
                            'city_id'=>$row->city_id,
                            'district_id'=>$row->district_id,
                        ])->where('id','<>',$row->id)->find();
                        if ($info){
                            exception('该区域分红池已存在');
                            return false;
                        }
                        $province = Area::get($row->province_id);
                        $row->province = $province->getAttr('name');
                        $city = Area::get($row->city_id);
                        $row->city = $city->getAttr('name');
                        $district = Area::get($row->district_id);
                        $row->district = $district->getAttr('name');
                    } elseif (!empty($row->province_id)&&!empty($row->city_id)){
                        $info = \app\admin\model\wanlshop\Pond::where([
                            'province_id'=>$row->province_id,
                            'city_id'=>$row->city_id,
                        ])->where('id','<>',$row->id)->find();
                        if ($info){
                            exception('该区域分红池已存在');
                            return false;
                        }
                        $province = Area::get($row->province_id);
                        $row->province = $province->getAttr('name');
                        $city = Area::get($row->city_id);
                        $row->city = $city->getAttr('name');
                    } elseif (!empty($row->province_id)){
                        $info = \app\admin\model\wanlshop\Pond::where([
                            'province_id'=>$row->province_id,
                        ])->where('id','<>',$row->id)->find();
                        if ($info){
                            exception('该区域分红池已存在');
                            return false;
                        }
                        $province = Area::get($row->province_id);
                        $row->province = $province->getAttr('name');
                    }*/
                }

        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','level','province','city','district','createtime']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function detail($ids = null)
    {
        //指定区域内入驻门店实付交易流水1%提成，门店锁定的所有客户在商城实付金额消费的1%提成(到佣金账户)
        //区域内入会商品收益15%(创业达人和会员入会付款金额的15%，和运营中心10%按照级差计算)(佣金)
        $row = $this->model->get($ids);

        $province_id = $row->province_id;

        $city_id = $row->city_id;

        $district_id = $row->district_id;

        //绑定分红池的用户
        $user_ids = User::where('FIND_IN_SET(:pond_ids,pond_ids)',['pond_ids' => $row->id])->column('id');

        if ($province_id&&$city_id&&$district_id){
            //区域下的店铺id
            $shop_ids = \app\admin\model\wanlshop\Shop::where(['province_id'=>$province_id,'city_id'=>$city_id,'district_id'=>$district_id])
                ->column('id');
        } elseif ($province_id&&$city_id){
            $shop_ids = \app\admin\model\wanlshop\Shop::where(['province_id'=>$province_id,'city_id'=>$city_id])
                ->column('id');
        } elseif ($province_id){
            $shop_ids = \app\admin\model\wanlshop\Shop::where(['province_id'=>$province_id])
                ->column('id');
        }
        $paylog_commission = 0;//店铺的线上/线下抽佣
        if ($shop_ids){
            //店铺的线下/线下总支付金额(不带消费金和消费券抵扣金额)
            $paylog_price = \app\api\model\wanlshop\Paylog::where('shop_id','in',$shop_ids)
                ->where('pay_status',1)->sum('price');
            $paylog_commission = $paylog_price*0.01;
        }

        $this->assign('paylog_commission',$paylog_commission);
        if ($row->level==0){
            $rate = 0.1;
        } else {
            $city_lower = $this->model->where(['province_id'=>$row->province_id,'city_id'=>$row->city_id,'level'=>0])
                ->where('district_id','>',0)->find();
            $district_lower = $this->model->where(['province_id'=>$row->province_id,'level'=>0])
                ->where('city_id','>',0)
                ->where('district_id','>',0)->find();
            if ($city_lower||$district_lower){
                $rate = 0.05;
            } else {
                $rate = 0.15;
            }
        }

        $pay_commission = 0;//商城的抽佣
        foreach ($user_ids as $k=>$v){
            $child = $this->getChildList($v);
            array_push($child,['id'=>$v]);
            $ids = array_column($child,'id');
            $pay_price = Pay::where('user_id','in',$ids)
                ->where('pay_state',1)
                ->where('type','goods')
                ->sum('price');
            $pay_commission+=$pay_price*$rate;
        }
        $this->assign('pay_commission',$pay_commission);
        return $this->view->fetch();

    }

    public function getChildList($user_id)
    {
        //第一次调用时初始化
        static $arr=array();
        //通过邀请码查询当前邀请码下级用户
        $data = collection(User::where(['parent_id'=>$user_id])->field('id')->select())->toArray();

        //遍历获取信息，调用当前方法直至没有下级用户
        foreach ($data as $key => $value) {
            $arr[] = $value;
            $this->getChildList($value['id']);
        }
        return $arr;
    }

}
